package cn.seaboot.admin.quartz.job;

import cn.seaboot.admin.mvc.SpringContext;
import cn.seaboot.admin.quartz.bean.ScheduleAction;
import cn.seaboot.admin.quartz.service.ScheduleActionService;
import cn.seaboot.commons.core.Asserts;
import cn.seaboot.commons.core.CommonUtils;
import cn.seaboot.commons.http.HttpClient;
import cn.seaboot.commons.http.HttpRequest;
import cn.seaboot.commons.http.RequestMethod;
import cn.seaboot.commons.http.call.TextHandler;
import cn.seaboot.commons.net.HttpUtils;
import com.alibaba.fastjson2.JSONObject;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * 定时任务
 * <p>
 * 通过接口调用的方式，触发定时任务
 *
 * @author Mr.css
 * @version 2024-12-26 17:27
 */
@DisallowConcurrentExecution
public class ScheduleRequestJob implements Job {

    private final Logger logger = LoggerFactory.getLogger(ScheduleRequestJob.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap();
        Long id = dataMap.getLong("id");
        Asserts.notNull(id, "id is null");

        ScheduleActionService scheduleActionService = SpringContext.getBean(ScheduleActionService.class);
        ScheduleAction task = scheduleActionService.queryById(id);

        HttpClient client = SpringContext.getBean(HttpClient.class);

        try {
            HttpRequest request;
            if (RequestMethod.POST.equals(task.getRequestMethod())) {
                request = client.post(URI.create(task.getRequestUrl()));
                if (CommonUtils.isNotEmpty(task.getRequestParams())) {
                    JSONObject obj = JSONObject.parseObject(task.getRequestParams());
                    request.setParameters(obj, Charset.defaultCharset());
                }
            } else {
                String url = task.getRequestUrl();
                if (CommonUtils.isNotEmpty(task.getRequestParams())) {
                    JSONObject obj = JSONObject.parseObject(task.getRequestParams());
                    HttpUtils.addMapToUrl(url, obj, Charset.defaultCharset().name());
                }
                request = client.get(URI.create(url));
            }

            String ret = request.execute(new TextHandler(Charset.defaultCharset().name()));
            logger.info("schedule request job response: {}", ret);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
